
class array_stack:
    '''
    固定数组实现栈
    '''
    def __init__(self, capacity: int):
        if capacity < 0: raise Exception('The init size is less than 0')
        self._data = [None] * capacity
        self._index = 0
    def peek(self) -> object:
        if self._index <= 0: raise Exception('no item!')
        return self._data[self._index - 1]
    def push(self, obj: object):
        if self._index >= len(self._data) : raise Exception('The stack is full.')
        self._data[self._index] = obj
        self._index += 1
    def pop(self) -> object:
        if self._index <= 0: raise Exception('no item!')
        self._index -= 1
        return self._data[self._index]

# 使用array数组实现队列,性能更好
#from array import array
#arr = array("q",[0]*capacity)

class array_queue:
    def __init__(self, capacity: int):
        if capacity < 0: raise Exception('The init size is less than 0')
#        assert (capacity >= 0), 'The init size is less than 0'   #debug
        self._data = [None] * capacity # 总长度
        self._length = 0  #当前使用得个数
        self._start = 0  # pop    永远指向下一个有元素位置
        self._end = 0    #push    永远指向下一个空位置
    
    def peek(self) -> object:
        if self._length <= 0: raise Exception('no item!')
        return self._data[self._start]
    def push(self, obj: object):
        if self._length >= len(self._data) : raise Exception('The stack is full.')
        self._length += 1 # 当前使用得个数加1
        self._data[self._end] = obj
        if (len(self._data) - 1) == self._end : # if (capacity - 1) == self._end
            self._end = 0
        else:
            self._end += 1
#        self._end = (self._end + 1)% capacity  #这句也可以
    def pop(self) -> object:
        if self._length <= 0: raise Exception('no item!')
        self._length -= 1
        tmp = self._start
        if self._start == (len(self._data) - 1):  # if self._start == (capacit - 1):
            self._start = 0
        else:
            self._start += 1
#        self._start = 0 if (self._start == (len(self._data) - 1)) else (self._start + 1)
#        self._start = (self._start + 1) % capacit
        return self._data[tmp]


a = array_queue(5)
#print(a.peek())
print(a.push(1))
print(a.push(2))
print(a.push(3))
print(a.push(4))
print(a.push(5))
#print(a.push(6))
print(a.peek())
print(a.pop())
print(a.peek())
print(a.pop())
print(a.peek())
print(a.pop())
print(a.peek())
print(a.pop())
print(a.peek())
print(a.pop())
print(a.peek())
print(a.pop())